package com.hcb.tonguetiphealth.widget.homepage;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.XmlParserManager;
import com.hcb.tonguetiphealth.model.Province;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class EditUserInfoWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "EditUserInfoWidget";
	private String url = Global.URL + Global.servlet_editinfo;
	
	private Activity ctx;
	private Handler mHandler;
	private LinearLayout bt_back;
	private Button bt_male, bt_female, bt_ok;
	private EditText et_name, et_email, et_remark, et_label, et_checkedBody;
	private TextView tv_province, tv_city;
	private String name, email, remark, label, province, city, sex, checkedBody;
	private User user;
	private ListView listView;
	private SelectionListAdapter adapter;
	private List<Province> provinceList;
	private List<String> strList;
	private int position = -1;
	private boolean isSucceed = false;
	private String strMsg;
	
	private PopupWindow popupWindow;
	
	public EditUserInfoWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.homepage_personal_editinfo, this); 
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.COMMIT_ING:
					showMessageDialog(ctx, "正在提交...");
					break;
				case MessageWhat.COMMIT_SUCCEED:
					showMessage(ctx, "修改成功");
					user.setRealName(name);
					user.seteMail(email);
					user.setSex(sex);
					user.setProvince(province);
					if(province.equals(city)) {
						user.setCity("");
					} else {
						user.setCity(city);
					}
					user.setInfo(remark);
					user.setLabels(label);
					user.setCheckedBody(checkedBody);
					bt_ok.setClickable(true);
					dismissMessageDialog();

					ctx.setContentView(new HomepagePersonalWidget(ctx));
					break;
				case MessageWhat.COMMIT_FAILD:
					showMessage(ctx, strMsg);
					bt_ok.setClickable(true);
					dismissMessageDialog();
					break;
				}
			}
		};
		tv_province = (TextView)findViewById(R.id.editinfo_member_belong_textview1);
		tv_city = (TextView)findViewById(R.id.editinfo_member_belong_textview2);
		et_name = (EditText)findViewById(R.id.edit_info_name_edittext);
		et_email = (EditText)findViewById(R.id.editinfo_member_email_edittext);
		et_remark = (EditText)findViewById(R.id.edit_info_remark_edittext);
		et_label = (EditText)findViewById(R.id.edit_info_label_edittext);
		et_checkedBody = (EditText)findViewById(R.id.edit_info_checked_body_edittext);
		bt_back = (LinearLayout)findViewById(R.id.editinfo_back_button);
		bt_male = (Button)findViewById(R.id.edit_info_male_button);
		bt_female = (Button)findViewById(R.id.edit_info_female_button);
		bt_ok = (Button)findViewById(R.id.editinfo_commit_button);
		bt_back.setOnClickListener(this);
		bt_ok.setOnClickListener(this);
		bt_male.setOnClickListener(this);
		bt_female.setOnClickListener(this);
		tv_province.setOnClickListener(this);
		tv_city.setOnClickListener(this);

		initData();
	}
	
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.editinfo_member_belong_textview1:
			popupWindow = makePopupWindow(ctx, 0);
			popupWindow.showAsDropDown(tv_province);
			break;
		case R.id.editinfo_member_belong_textview2:
			popupWindow = makePopupWindow(ctx, 1);
			popupWindow.showAsDropDown(tv_city);
			break;
		case R.id.editinfo_back_button:
			ctx.setContentView(new HomepagePersonalWidget(ctx));
			break;
		case R.id.edit_info_male_button:
			bt_male.setBackgroundResource(R.drawable.checkbox_1);
			bt_female.setBackgroundResource(R.drawable.checkbox_2);
			sex = "1";
			break;
		case R.id.edit_info_female_button:
			bt_male.setBackgroundResource(R.drawable.checkbox_2);
			bt_female.setBackgroundResource(R.drawable.checkbox_1);
			sex = "2";
			break;
		case R.id.editinfo_commit_button:
			checkInfo();
			break;
		default:
			break;
		}
	}
	private void checkInfo() {
		name = et_name.getText().toString();
		email = et_email.getText().toString();
		remark = et_remark.getText().toString();
		label = et_label.getText().toString();
		checkedBody = et_checkedBody.getText().toString();
		province = tv_province.getText().toString();
		city = tv_city.getText().toString();
		if(StringUtils.isEmpty(city)) {
			city = province;
		}
		if(!StringUtils.isEmpty(email) && !IsValidEmail(email)) {
			showMessage(ctx, "请填写正确的电子邮件");
			return;
		}
		bt_ok.setClickable(false);
		mHandler.sendEmptyMessage(MessageWhat.COMMIT_ING);
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userId", user.getUserId()));
					params.add(new BasicNameValuePair("name", name));
					params.add(new BasicNameValuePair("email", email));
					params.add(new BasicNameValuePair("checkedBody", checkedBody));
					params.add(new BasicNameValuePair("remark", remark));
					params.add(new BasicNameValuePair("label", label));
					params.add(new BasicNameValuePair("sex", sex));
					params.add(new BasicNameValuePair("province", province));
					params.add(new BasicNameValuePair("city", city));
					response = HttpUtils.Post(url, params);
					
					if(Global.DEBUG) {
						System.out.println("-----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						isSucceed = true;
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
						mHandler.sendEmptyMessage(MessageWhat.COMMIT_SUCCEED);
					} else {
						strMsg = jManager.getMsg();
						mHandler.sendEmptyMessage(MessageWhat.COMMIT_FAILD);
					}
				} else {
					strMsg = "修改失败";
					mHandler.sendEmptyMessage(MessageWhat.COMMIT_FAILD);
				}
			}
		}.start();
	}
	
	private void initData() {
		strList = new ArrayList<String>();
		if(Global.user != null) {
			user = Global.user;
			et_name.setText(user.getRealName());
			et_email.setText(user.geteMail());
			et_remark.setText(user.getInfo());
			et_label.setText(user.getLabels());
			tv_province.setText(user.getProvince());
			city = user.getCity();
			if(!StringUtils.isEmpty(city)) {
				tv_city.setText(user.getCity());
				tv_city.setVisibility(TextView.VISIBLE);
			}
			
			String sSex = user.getSex();
			if(StringUtils.isEmpty(sSex)) {
				bt_male.setBackgroundResource(R.drawable.checkbox_2);
				bt_female.setBackgroundResource(R.drawable.checkbox_2);
				sex = "0";
			} else {
				if(sSex.equals("1")) {
					bt_male.setBackgroundResource(R.drawable.checkbox_1);
					bt_female.setBackgroundResource(R.drawable.checkbox_2);
					sex = "1";
				} else if(sSex.equals("1")) {
					bt_male.setBackgroundResource(R.drawable.checkbox_2);
					bt_female.setBackgroundResource(R.drawable.checkbox_1);
					sex = "2";
				}
			}
		}
	}
	
	private void initDataOfProvinceOrCity(int flag) {
		AssetManager assetManager = ctx.getAssets();
		InputStream inputStream = null; 
		if(0 == flag) {
			try { 
			   inputStream = assetManager.open("provinces.xml"); 
			   provinceList = XmlParserManager.getProvinces(inputStream);
			   strList.clear();
			   for(Province p : provinceList) {
				   strList.add(p.getName());
			   }
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if(1 == flag) {
			try { 
				if(-1 == position) {
					inputStream = assetManager.open("provinces.xml"); 
				    provinceList = XmlParserManager.getProvinces(inputStream);
				    strList.clear();
				    for(int i=0; i<provinceList.size(); i++) {
					   if(user.getProvince().contains(provinceList.get(i).getName())) {
						   position = i;
						   break;
					   }
				    }
				}
			   String tagCity = "city_" + position +".xml";
			   inputStream = assetManager.open(tagCity); 
			   strList = XmlParserManager.getCitys(inputStream);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			
		}
	}
	private void setCityVisibility(boolean visible) {
		//设置city是否可选
		if(visible) {
			tv_city.setVisibility(TextView.VISIBLE);
		} else {
			tv_city.setVisibility(TextView.INVISIBLE);
		}
		tv_city.setText("");
	}
	//创建一个包含自定义view的PopupWindow
	private PopupWindow makePopupWindow(Context cx, final int flag) {
	    PopupWindow window;
	    window = new PopupWindow(cx);
	    
	    LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.drinks_book_dialog_list, null); 
        listView = (ListView)view.findViewById(R.id.drinks_book_dialog_listview);
        initDataOfProvinceOrCity(flag);
        adapter = new SelectionListAdapter(ctx, strList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				position = arg2;
				String result = (String)arg0.getAdapter().getItem(arg2);
				if(0 == flag) {
					tv_province.setText(result);
					setCityVisibility(provinceList.get(arg2).isHasCitys());
				} else if(1 == flag) {
					tv_city.setText(result);
				} else {
					
				}
				
				popupWindow.dismiss();
			}
		});
	    
	    final Resources res = cx.getResources();
	    view.setBackgroundColor(res.getColor(R.color.transparent2));
	    view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
	    //设置PopupWindow显示和隐藏时的动画
	    window.setAnimationStyle(R.style.AnimationFade);
	    //设置PopupWindow的大小（宽度和高度）
	    window.setWidth(tv_city.getWidth());
	    //window.setWidth(res.getDimensionPixelSize(R.dimen.page_window_width));
	    window.setHeight(res.getDimensionPixelSize(R.dimen.page_window_height));
	    //设置PopupWindow的内容view
	    window.setContentView(view);
        //设置PopupWindow外部区域是否可触摸
        window.setOutsideTouchable(true);
        //设置焦点，必须设置，否则listView无法响应
        window.setFocusable(true);
        window.update();
        
	    return window;
	}
	@Override
	public void notifyAdapter() {
		
	}
}
